package com.demo.spark.rdd;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class RddFoldMax {
    public static void main(String[] args) {

        SparkConf sparkConf = new SparkConf();
        sparkConf.setAppName("rdd count by key");
        sparkConf.setMaster("local");
        JavaSparkContext javaSparkContext = new JavaSparkContext(sparkConf);
        javaSparkContext.setLogLevel("error");

        List<Integer> data = Arrays.asList(5, 1, 1, 4, 4, 2, 2);
        JavaRDD<Integer> javaRDD = javaSparkContext.parallelize(data,3);
        JavaRDD<String> stringJavaRDD = javaRDD.mapPartitionsWithIndex(new Function2<Integer, Iterator<Integer>, Iterator<String>>() {
            @Override
            public Iterator<String> call(Integer v1, Iterator<Integer> v2) throws Exception {
                LinkedList<String> linkedList = new LinkedList<String>();
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("partition_"+v1+",data : ");
                while (v2.hasNext()) {
                    Integer next = v2.next();
                    stringBuffer.append(next+",");
                }
                linkedList.add(stringBuffer.toString());
                return linkedList.iterator();
            }
        },false);
        List<String> collect = stringJavaRDD.collect();
        for (String s : collect) {
            System.out.println(s);
        }

        Integer fold = javaRDD.fold(0, new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer v1, Integer v2) throws Exception {
                System.out.println(v1);
                System.out.println(v2);
                return Math.max(v1, v2);
            }
        });
        System.out.println(fold);

    }
}
